package com.baizhi.service.impl;

import com.baizhi.entity.Book;
import com.baizhi.mapper.BookMapper;
import com.baizhi.service.BookService;
import com.baizhi.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class BookServiceImpl implements BookService {
    @Override
    public List<Book> showBooks(Integer pageNum, Integer pageSize) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        List<Book> books = null;
        try{
            BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
            books = bookMapper.selectBooks(pageNum,pageSize);
            sqlSession.commit();
        }catch (Exception e){
            sqlSession.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            MyBatisUtils.close(sqlSession);
        }
        return books;
    }

    @Override
    public Book showBookById(Integer id) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        Book book = null;
        try{
            BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
            book = bookMapper.selectBookById(id);
            sqlSession.commit();
        }catch (Exception e){
            sqlSession.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            MyBatisUtils.close(sqlSession);
        }
        return book;
    }

    @Override
    public void addBook(Book b) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        try{
            BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
            bookMapper.insertBook(b);
            sqlSession.commit();
        }catch (Exception e){
            sqlSession.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            MyBatisUtils.close(sqlSession);
        }
    }

    @Override
    public void removeBookById(Integer id) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        try{
            BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
            bookMapper.deleteBookById(id);
            sqlSession.commit();
        }catch (Exception e){
            sqlSession.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            MyBatisUtils.close(sqlSession);
        }
    }

    @Override
    public void updateBook(Book b) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        try{
            BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
            bookMapper.updateBook(b);
            sqlSession.commit();
        }catch (Exception e){
            sqlSession.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            MyBatisUtils.close(sqlSession);
        }
    }
}
